package com.cherry.ssmsimple.controller;

import com.cherry.ssmsimple.pojo.Blog;
import com.cherry.ssmsimple.service.BlogService;
import com.cherry.ssmsimple.util.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    @Qualifier("blogService")
    BlogService blogService;

    @GetMapping("/allBlog")
    public String findAll(Model model) {
        List<Blog> all = blogService.findAll();
        model.addAttribute("list", all);
        return "allBlog";
    }

    @PostMapping("/addBlog")
    public String addBlog(String blogName, String blogAuthor) {
        Blog blog = new Blog();
        blog.setId(IDUtil.genId());
        blog.setTitle(blogName);
        blog.setAuthor(blogAuthor);
        blog.setCreateTime(new Date());

        blogService.addBlog(blog);

        return "redirect:/blog/allBlog";
    }

    @PostMapping("/updateBlog")
    public String updateBlog(Blog blog) {
        blogService.update(blog);
        return "redirect:/blog/allBlog";
    }

    @RequestMapping("/del/{blogId}")
    public String updateBlog(@PathVariable("blogId") String id) {
        blogService.delById(id);
        return "redirect:/blog/allBlog";
    }


    //---------------跳转页-------------------//
    @GetMapping("/toAddBlog")
    public String toAddBlog() {
        return "toAddBlog";
    }


    @RequestMapping("/toUpdateBlog")
    public String toUpdateBlog(Model model, String id) {
        Blog blog = blogService.findById(id);
        model.addAttribute("blog", blog);
        return "toUpdateBlog";
    }

}
